package com.game;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemLongClickListener;

public abstract class ViewTableActivity extends ListActivity{
	protected DBAdapter myDBAdapter;
	protected Cursor cursor;
	protected SimpleCursorAdapter cursorAdapter;
	protected int layoutId;
	protected String myTable;
	protected int [] TO_ITEM;
	
	protected abstract void initalize();
	
	protected abstract String getItemName(int Id);
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initalize();
		
		myDBAdapter = ((txtGameApplication)this.getApplication()).getDatabaseAdapter();
		
		cursor = getCursor(myTable);
		showItems(cursor,myTable);
		
		
		getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> parent,View v,int position, long id){
				deleteGameItemDialog(cursor.getInt(cursor.getColumnIndex("_id")),myTable);
				
				return true;
			}
		});
	}
	
	private Cursor getCursor(String tableName){
			Cursor myCursor = myDBAdapter.getAllItemCursor(tableName);
			startManagingCursor(myCursor);
			return myCursor;
	}
	
	private void showItems(Cursor cursor,String tableName){
		cursorAdapter = new SimpleCursorAdapter(this,layoutId,cursor,myDBAdapter.getFrom(tableName),TO_ITEM);
		setListAdapter(cursorAdapter);
	}
	
	
    private void deleteGameItemDialog(final int itemId,final String tableName){
		String title ="Would you Like to delete the following Item?";
		String buttonOk = "Ok";
		String buttonCancel = "Canel";
		String itemName = getItemName(itemId);
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setTitle(title);
		ad.setMessage(itemName);
		ad.setPositiveButton(buttonOk, new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int arg1){
				myDBAdapter.removeItem(itemId,tableName);
				cursorAdapter.getCursor().requery();
			}
		});
		
		ad.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int arg1){
				
			}
		});
		
		ad.show();
    }
	

	
}
